package master.common.encoding;

import master.common.utils.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
public class MD5 {

    private MD5() {
    }

    /**
	 * 返回字符串经过MD5运算之后的摘要
	 * @param origin
	 * @return MD5摘要
	 */
	public static String MD5Encode(String origin) {
		String resultString = null;

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = StringUtil.byteArrayToHexString(md.digest(origin.getBytes("UTF-8")));
		} catch (Exception ex) {
		}
		return resultString;
	}

	/**
	 * 计算输入字节数组的MD5摘要
	 * @param input
	 * @return 返回MD5摘要
	 * @throws java.security.NoSuchAlgorithmException
	 */
	public static byte[] MD5Digest(byte[] input) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		return md.digest(input);
	}

	/**
	 * 计算输入流中内容的MD5摘要
	 * @param in 输入流（用户有责任在调用本方法之后关闭输入流，本方法不会关闭输入流）
	 * @return 返回MD5摘要
	 * @throws NoSuchAlgorithmException
	 * @throws java.io.IOException
	 */
	public static byte[] MD5Digest(InputStream in) throws NoSuchAlgorithmException, IOException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = in.read(buffer)) != -1) {
			md.update(buffer, 0, len);
		}
		return md.digest();
	}
}
